package com.security.auth.server;

import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

/**
 * @Author yanggld
 * @Date 2020/3/9-17:33
 * 从内存读取配置
 */
//@Configuration
//@EnableAuthorizationServer
public class Oauth2AuthServerMemory extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("isAuthenticated()");
        super.configure(security);
    }

    /**
     * order client获取的token可以访问的资源服务器 orderService123
     * orderService client获取的token可以访问的资源服务器 orderService
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("order").secret(passwordEncoder.encode("123456")).scopes("read", "write")
            .accessTokenValiditySeconds(3600).resourceIds("orderService123").authorizedGrantTypes("password").and()
            .withClient("orderService").secret(passwordEncoder.encode("123456")).scopes("read", "write")
            .accessTokenValiditySeconds(3600).resourceIds("orderService");
        super.configure(clients);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
        super.configure(endpoints);
    }
}
